import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

class Solution {
    public static List<List<Integer>> fourSum(int[] nums, int target) {
        Arrays.sort(nums);
        List<List<Integer>> ret = new ArrayList<>();
        int n = nums.length;
        for (int i = 0; i < n; ) {
            if(nums[i] > 0 && target < 0) break;
            long target1 = target - nums[i];
            for (int j = i + 1; j < n;) {
                if(nums[j] > 0 && target1 < 0) break;
                int left = j + 1,right = n - 1;
                long target2 =  target1 - nums[j];
                while (left < right) {
                    int sum = nums[left] + nums[right];
                    if (sum < target2) left++;
                    else if (sum > target2) right--;
                    else {
                        List<Integer> list = new ArrayList<>();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[left]);
                        list.add(nums[right]);
                        ret.add(list);
                        left++;right--;
                        while(left < right && nums[left] == nums[left-1]) left++;
                        while(left < right && nums[right] == nums[right + 1]) right--;
                    }
                }
                j++;
                while(j < n && nums[j] == nums[j-1]) j++;
            }
            i++;
            while(i < n && nums[i] == nums[i-1]) i++;
        }
        return ret;
    }

    public static void main(String[] args) {
        int[] nums = {-1000000000,-1000000000,1000000000,-1000000000,-1000000000};
        List<List<Integer>> ret = fourSum(nums,294967296);
        System.out.println(ret);
    }
}